<?php
class Model_Search {
	
	protected $_searchIndexPath; //path to initial data folder
	protected $db; //database adapter
	protected $db_table_name; //in what table to search
	

	
	public function __construct($db_table_name) {
		
		setlocale(LC_CTYPE, 'ru_RU.UTF-8');
		
		$this->db_table_name = $db_table_name;
		
		$this->_searchIndexPath = APPLICATION_PATH . '/data/search-index/' . $this->db_table_name;
		$this->db = Zend_Db_Table_Abstract::getDefaultAdapter ();
		set_time_limit ( 0 );
		Zend_Search_Lucene_Analysis_Analyzer::setDefault ( new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive () );
	
	}
	
	public function addToIndex($id, $name, $surname, $login) {
		try {
			$index = Zend_Search_Lucene::open ( $this->_searchIndexPath );
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "<p class=\"ui-bad-message\">Can't open search index: {$e->getMessage()}</p>";
		}
		
		try {
			$doc = new Zend_Search_Lucene_Document ();
			
			$doc->addField ( Zend_Search_Lucene_Field::keyword ( 'link_id', $id ) );
			$doc->addField ( Zend_Search_Lucene_Field::Text ( 'login', $login, 'UTF-8' ) );
			$doc->addField ( Zend_Search_Lucene_Field::Text ( 'name', $name, 'UTF-8' ) );
			$doc->addField ( Zend_Search_Lucene_Field::Text ( 'surname', $surname, 'UTF-8' ) );
			
			$index->addDocument ( $doc );
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "<p class=\"ui-bad-message\">Indexing error: {$e->getMessage()}</p>";
		}
	}
	
	
	/******** USE ONLY WHEN NEEEED ********/
	//change access to public and direct use from URL
	private function createIndex() {
		$this->recursive_remove_directory ( $this->_searchIndexPath, TRUE );
		try {
			$index = Zend_Search_Lucene::create ( $this->_searchIndexPath );
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "<p class=\"ui-bad-message\">Can't create search index: {$e->getMessage()}</p>";
		}
		
		echo "Index was created!!!";
	}
	
	private function updateIndex() {

		try {
			$index = Zend_Search_Lucene::open ( $this->_searchIndexPath );
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "<p class=\"ui-bad-message\">Can't create new search index: {$e->getMessage()}</p>";
		}
		
		try {
			//выбираем все слова из БД
			$words = $this->db->fetchAll ( $this->db->select ()->from ( $this->db_table_name, array ('id', 'login','name', 'surname' ) ) );
			
			$i = 0;
			foreach ( $words as $w ) {
				$doc = new Zend_Search_Lucene_Document ();
				
				//need to name link_id, 'cause it count 'id' it's own? not that name)
				$doc->addField ( Zend_Search_Lucene_Field::keyword ( 'link_id', $w ['id'] ) );
				$doc->addField ( Zend_Search_Lucene_Field::Text ( 'login', $w ['login'], 'UTF-8' ) );
				$doc->addField ( Zend_Search_Lucene_Field::Text ( 'name', $w ['name'], 'UTF-8' ) );
				$doc->addField ( Zend_Search_Lucene_Field::Text ( 'surname', $w ['surname'], 'UTF-8' ) );
				$index->addDocument ( $doc );
				$i ++;
			}
		
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "<p class=\"ui-bad-message\">Indexing error: {$e->getMessage()}</p>";
		}
		
		//let's clean up some
		$index->optimize ();
		
		echo "<p class=\"ui-good-message\">
    			Search index created again. Words added: {$i}. <br />
    			Index was optimized.</p>";
	}
	
	
	function update_item($id,$name ,$surname, $login) {
		$this->remove_item($id);
		$this->addToIndex($id, $name, $surname, $login);
	}
	
	
	function remove_item($id){
		
			
			$index = Zend_Search_Lucene::open ( $this->_searchIndexPath );
			$hits = $index->find('link_id:' . $id);
			
			foreach ($hits as $hit) {
				$index->delete($hit->id);
			}
			$index->commit();
	}
	
	
	/**
	 * recursive_remove_directory( directory to delete, empty )
	 * expects path to directory and optional TRUE / FALSE to empty
	 *
	 * @param $directory
	 * @param $empty TRUE - just empty directory
	 */
	function recursive_remove_directory($directory, $empty = FALSE) {
		if (substr ( $directory, - 1 ) == '/') {
			$directory = substr ( $directory, 0, - 1 );
		}
		if (! file_exists ( $directory ) || ! is_dir ( $directory )) {
			return FALSE;
		} elseif (is_readable ( $directory )) {
			$handle = opendir ( $directory );
			while ( FALSE !== ($item = readdir ( $handle )) ) {
				if ($item != '.' && $item != '..') {
					$path = $directory . '/' . $item;
					if (is_dir ( $path )) {
						$this->recursive_remove_directory ( $path );
					} else {
						unlink ( $path );
					}
				}
			}
			closedir ( $handle );
			if ($empty == FALSE) {
				if (! rmdir ( $directory )) {
					return FALSE;
				}
			}
		}
		return TRUE;
	}
	
	/**
	 * Search by query
	 * 
	 * @param $query search query
	 * @return array Zend_Search_Lucene_Search_QueryHit
	 */
	public function search($query) {
		try {
			$index = Zend_Search_Lucene::open ( $this->_searchIndexPath );
		} catch ( Zend_Search_Lucene_Exception $e ) {
			echo "Error:{$e->getMessage()}";
		}
		
		$userQuery = Zend_Search_Lucene_Search_QueryParser::parse ( $query ,'utf-8');
		
		return $index->find ( $userQuery );
	}
}